//
//  ByNetBase.m
//  beibei_ios
//
//  Created by hebidu on 16/4/15.
//  Copyright © 2016年 hebidu. All rights reserved.
//

#import "ByNetBaseApi.h"
#import "ByCoreCryptDes.h"

#import "ByNetBaseResponse.h"           // 返回model
#import "ByNetBaseError.h"              // 错误model



#define UPLOAD_ERROR_STRING_CODE -67
#define UPLOAD_ERROR_OTHER_CODE -76

@implementation ByNetBaseApi

/** 返回数据是否是正确的 */
+ (BOOL)returnDataIsCurrect:(id)data type:(ByNetDataType)type {
    
    switch (type) {
        case ByNetDataTypeString:
        {
            if ([data isKindOfClass:[NSString class]]) {
                return YES;
            } else {
                return NO;
            }
        }
            break;
        case ByNetDataTypeArray:
        {
            if ([data isKindOfClass:[NSArray class]]) {
                return YES;
            } else {
                return NO;
            }
        }
            break;
        case ByNetDataTypeDictionary:
        {
            if ([data isKindOfClass:[NSDictionary class]]) {
                return YES;
            } else {
                return NO;
            }
        }
            break;
        default:
            break;
    }
}




+ (void)post:(NSString *)requestId
      params:(NSDictionary *)params
     success:(void(^)(id result))success
     failure:(void(^)(NSError *error))failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 默认超时时间30秒
    manager.requestSerializer.timeoutInterval = 30;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript", nil];
    
    [manager.requestSerializer setValue:@"SocketLog(tabid=2&client_id=slog_fc68e9)" forHTTPHeaderField:@"SocketLog"];
    
    // 数据加密
    NSMutableDictionary *m_params = [[NSMutableDictionary alloc] initWithDictionary:params];
    [m_params setObject:@"prod" forKey:@"env"];

    if (BY_USER && BY_USER.token) {
        [m_params setObject:BY_USER.token forKey:@"token"];
    }
    [m_params setObject:APP_VERSION forKey:@"app_version"];
    [m_params setObject:@"ios" forKey:@"app_type"];
    
    NSString *str = [NSString stringWithFormat:@"%@%@",BOYE_BASE_URL,requestId];
    
    [manager POST:str
       parameters:m_params
         progress:^(NSProgress * uploadProgress){
             
             
         }
          success:^(NSURLSessionDataTask *operation ,id responseObject) {
              
              
              NSDictionary *dic = responseObject;
              NSString *code = dic[@"code"];
              
              if (code.integerValue == 1999) {
                  
                  [UIAlertView showWithTitle:@"版本更新" message:@"app有新版本，只有更新到新版本app才能正常使用" cancelButtonTitle:nil otherButtonTitles:@[@"去更新"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                      
                      //云彩
                      if ([APP_SCHEME isEqualToString:@"com.itboye.lottery"]) {
                          
                          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://dafuit.com/app.php/asdsdsot"]];
                          
                          //天天购彩票
                      }else if ([APP_SCHEME isEqualToString:@"net.ixiaoyuan.a"]){
                          
                          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.dwz.am/l8s53ff.html"]];
                          
                          //测试
                      }else if ([APP_SCHEME isEqualToString:@"rrgc.8raw.com"]){
                          
                          [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://baidu.com"]];
                      }
                  }];
                  
                  return ;
              }
              
              
              if (code.integerValue == 0) {
                  
                   success(responseObject);
                  
              }else{
                  
                  NSError *error = [[NSError alloc] initWithDomain:dic[@"msg"] code:code.integerValue userInfo:nil];
                  failure(error);
                  NSLog(@"接口 %@  error = %@",str, error);
              }
              
          } failure:^(NSURLSessionDataTask *operation , NSError *error){
               NSLog(@"接口%@  error = %@",str, error);
              
              ByNetBaseError *errorModel = [[ByNetBaseError alloc] initWithError:error];
              [errorModel setFailourBlock:^(NSString *errorDesc, NSInteger code) {
                  NSError *error1 = [[NSError alloc] initWithDomain:errorDesc code:code userInfo:nil];
                  failure(error1);
              }];
              [errorModel errorAnalysis];
          }];
}


+ (void)get:(NSString *)requestId
     params:(NSDictionary *)params
    success:(void(^)(id result))success
    failure:(void(^)(NSError *error))failure{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 默认超时时间30秒
    manager.requestSerializer.timeoutInterval = 30;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json", @"text/javascript", nil];
    
    [manager.requestSerializer setValue:@"SocketLog(tabid=2&client_id=slog_fc68e9)" forHTTPHeaderField:@"SocketLog"];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:1];
    [dic setObject:@"prod" forKey:@"env"];
    if (BY_USER && BY_USER.token) {
         [dic setObject:BY_USER.token forKey:@"token"];
         [dic setObject:BY_USER.uid forKey:@"uid"];
    }
    [dic setObject:APP_VERSION forKey:@"app_version"];
    [dic setObject:@"ios" forKey:@"app_type"];
    NSString *str = [NSString stringWithFormat:@"%@%@&&app_type=%@&&app_version=%@&&token=%@&&env=%@",BOYE_BASE_URL,requestId,dic[@"app_type"],dic[@"app_version"],dic[@"token"],dic[@"env"]];
    [manager GET:str parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"原始数据 responseObject = %@", responseObject);
        
        NSDictionary *dic = responseObject;
        NSString *code = dic[@"code"];
        
        if (code.integerValue == 1999) {
            
            [UIAlertView showWithTitle:@"版本更新" message:@"app有新版本，只有更新到新版本app才能正常使用" cancelButtonTitle:nil otherButtonTitles:@[@"去更新"] tapBlock:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                //云彩
                if ([APP_SCHEME isEqualToString:@"com.itboye.lottery"]) {
                    
                   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://dafuit.com/app.php/asdsdsot"]];
               
                //天天购彩票
                }else if ([APP_SCHEME isEqualToString:@"net.ixiaoyuan.a"]){
                    
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.dwz.am/l8s53ff.html"]];
                 
                //测试
                }else if ([APP_SCHEME isEqualToString:@"rrgc.8raw.com"]){
                   
                     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://baidu.com"]];
                }
            }];
            
            return ;
        }
        
        if (code.integerValue == 0) {
            
            success(responseObject);
            
        }else{
            
            NSLog(@"失败 code = %@",code);
            NSError *error = [[NSError alloc] initWithDomain:responseObject[@"msg"] code:code.integerValue userInfo:nil];
            failure(error);
            NSLog(@"接口 %@  error = %@",str, error);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        ByNetBaseError *errorModel = [[ByNetBaseError alloc] initWithError:error];
        [errorModel setFailourBlock:^(NSString *errorDesc, NSInteger code) {
            NSError *error1 = [[NSError alloc] initWithDomain:errorDesc code:code userInfo:nil];
            failure(error1);
        }];
        [errorModel errorAnalysis];
    }];
}


/** 统一处理错误时的信息 */
+ (void)operateFailure:(void(^)(NSURLSessionDataTask *operation, NSError *error))failure
             errorDesc:(NSString *)desc
                  code:(NSInteger)code {
    
    if (failure) {
        NSError *error = [[NSError alloc] initWithDomain:desc code:code userInfo:nil];
        failure(nil, error);
    } else {
        //[ByCoreToolAlert showFailureWithText:@""];
    }
}


+ (BOOL)failureProcess:(NSError * )error{
    
    if (error.code == NSURLErrorTimedOut) {
        [ByCoreToolAlert showFailureWithText:@"请求超时!"];
        return YES;
    }
    if(error.code == NSURLErrorBadURL) {
        [ByCoreToolAlert showFailureWithText:@"非法请求地址!"];
        return YES;
    }
    if(error.code == NSURLErrorCannotFindHost) {
        [ByCoreToolAlert showFailureWithText:@"无法查找远程主机!"];
        return YES;
    }
    if(error.code == NSURLErrorCannotConnectToHost){
        [ByCoreToolAlert showFailureWithText:@"远程主机无法连接!"];
        return YES;
    }
    if([error.domain isEqualToString: @"NSURLErrorDomain"]){
        [ByCoreToolAlert showFailureWithText:@"请求失败,请重试!"];
        return YES;
    }
    
    return NO;
}


+(NSMutableDictionary * ) desCrypt:(id)param{
    
    NSString *jsonString;
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&error];
    
    if (!jsonData) {
        NSLog(@"byit____Got an error: %@", error);
    } else {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableDictionary * tmp = [[NSMutableDictionary alloc]init];
    
    NSString * postDes =  [ByCoreCryptDes desEncode:jsonString :BOYE_CLIENT_SECRET];
    
    [tmp setObject: [ByCoreCrypt base64Encode:postDes] forKey:@"itboye"];
    [tmp setObject: @"itboye" forKey:@"copyright"];

    return tmp;
}


+(NSMutableDictionary *) getData:(NSString *)requestId
                         apiType:(NSString *)type
                       apiVerson:(NSInteger)ver
                          params:(NSDictionary *)params{
    NSMutableDictionary * dic = [[NSMutableDictionary alloc] init];
    
    NSNumber * timestamp = [NSNumber numberWithDouble:[NSDate currentDateTimeInterval]];
    
    NSString * time = [NSString stringWithFormat:@"%ld",timestamp.integerValue];
    
    [dic setValue:time forKey:@"time"]; // 时间戳参数
    
    [dic setValue:requestId forKey:@"notify_id"]; //
    
    // 如果没有业务参数（params == nil，则在加密中做了处理
    NSString *dataStr;
    dataStr = [ByCoreCrypt encryptString:params]; // 明文参数加密
    
    
    [dic setValue:@"md5" forKey:@"alg"]; // 加密方式
    
    [dic setValue:dataStr forKey:@"data"]; // 加密后的数据参数
    [dic setValue:type forKey:@"type"]; // 请求类型参数
    [dic setValue:@(ver) forKey:@"api_ver"]; // 版本号，和服务器一样才能返回正确数据
    
    
    NSArray *numAry = [APP_VERSION componentsSeparatedByString:@"."];
    
    NSInteger versionNum = [numAry[0] integerValue] * 10000 + [numAry[1] integerValue] * 100 + [numAry[2] integerValue];
    [dic setValue:@(versionNum) forKey:@"app_version"]; // 版本号
    [dic setValue:@"ios" forKey:@"app_type"]; // 类型
    
    NSString *signStr = [ByCoreCrypt signData:dic];
    [dic setValue:signStr forKey:@"sign"]; // 签名
    return dic;
}


@end
